
package com.winning.sx.microframework.controller.busi;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.winning.dapi.data.entity.DataTable;
import com.winning.sx.microframework.common.util.Constains;
import com.winning.sx.microframework.common.util.FileTools;
import com.winning.sx.microframework.common.util.FlowCodeUtil;
import com.winning.sx.microframework.common.util.SqlTool;
import com.winning.sx.microframework.model.exception.CustomException;
import com.winning.sx.microframework.model.manage.LoginSession;
import com.winning.sx.microframework.model.message.AjaxDataResponseMessage;
import com.winning.sx.microframework.model.message.AjaxTableResponseMessage;
import com.winning.sx.microframework.service.EasyService;
import com.winning.sx.microframework.service.base.EquipmentService;
import com.winning.sx.microframework.service.base.MessageService;
import com.winning.sx.microframework.service.sysmanage.ConstService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/busi/equipment/manage")
public class EquipmentMaintainManageController {
    @Autowired
    EasyService easyService;
    @Autowired
    ConstService service;
    @Autowired
    MessageService messageService;
    @Autowired
    EquipmentService equipmentService;
    @Autowired
    ConstService constService;

    @RequestMapping(value = {"/", ""})
    public ModelAndView init() throws IOException, CustomException, SQLException {
        ModelAndView mv = new ModelAndView("/busi/equipmentMaintainManage");
        List state = service.queryCount("201");
        mv.addObject("state", state);
        List brand = service.queryCount("300");
        mv.addObject("brand", brand);
        List way = service.queryCount("600");
        mv.addObject("way", way);
        List question = service.queryCount("110");
        mv.addObject("question", question);
        List dataType = service.queryCount("111");
        mv.addObject("dataType", dataType);
        List level = service.queryCount("114");
        mv.addObject("level", level);
        List repairState = service.queryCount("115");
        mv.addObject("repairState", repairState);

        Map eqRootClassP = new HashMap();
        eqRootClassP.put("superId", "0");
        eqRootClassP.put("validFlag", "100001");
        DataTable eqRootClassS = easyService.queryList("BASE_EqClass", eqRootClassP);
        List eqRootClass = eqRootClassS.getDataRows();
        mv.addObject("eqRootClass", eqRootClass);

        Map map = new HashMap();
        List eqClass = easyService.querySql("SELECT " +
                "  c1.name + '-' + c2.name name, " +
                "  c2.code " +
                "FROM BASE_EqClass c1 " +
                "  RIGHT JOIN BASE_EqClass c2 ON c1.id = c2.superId " +
                "WHERE c2.validFlag = '100001' AND c1.id IS NOT NULL ", map).getDataRows();
        mv.addObject("eqClass", eqClass);

        List warehouseList = easyService.querySql("select * from BASE_Warehouse where validFlag = '100001'", map).getDataRows();
        mv.addObject("warehouseList", warehouseList);

        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        Map<String, String> param = new HashMap();
        param.put("organizationType", "400001");
        param.put("superOrganizationId", login.getSuperOrgId());
        mv.addObject("organizationName", JSON.toJSON(service.queryMyOrg(param)).toString());
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = {"/queryList"})
    public AjaxTableResponseMessage queryMessageList(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            Map paramNew = new HashMap();
            if (!"0".equals(param.get("type"))) {
                String code = param.get("type").toString().trim();
                paramNew.put("oneCode", code);
            }
            if (!"0".equals(param.get("brand"))) {
                String constType = param.get("brand").toString().trim();
                paramNew.put("brandCode", constType);
            }
            if (!"0".equals(param.get("repairState"))) {
                String repairState = param.get("repairState").toString().trim();
                paramNew.put("repairState", repairState);
            }
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            if ("0".equals(param.get("oneOrganization"))) {
                paramNew.put("organizationId", login.getSuperOrgId());
            } else {
                paramNew.put("organizationId", param.get("oneOrganization"));
            }
            if (!"".equals(param.get("name").trim()) && param.get("name").trim() != null) {
                paramNew.put("name", param.get("name").trim());
            }
            Map orgParam = new HashMap();
            orgParam.put("superOrganizationId", paramNew.get("organizationId").toString());
            orgParam.put("organizationType", "400001");
            String orgs = service.queryMyOrg(orgParam).get("orgs").toString();
            if (orgs.length() == 0) {
                orgs = paramNew.get("organizationId").toString();
            } else {
                orgs += ("," + paramNew.get("organizationId").toString());
            }
            //系统管理员特殊处理
            if ("0".equals(param.get("organizationId"))) {
                paramNew.put("organizationId", null);
            }
            paramNew.put("b_createTime", param.get("b_createTime"));
            paramNew.put("e_createTime", param.get("e_createTime"));
            String sql = "select m.id,m.flowCode,case when op.id is null then o.name else op.name+'-'+o.name end organizationName,e.model, " +
                    "e.name,e.barCode barCode,  q.code QRcode,m.questionDescripe questionDescribe, m.equipmentId, e.oneCode," +
                    " e.usePosition,m.questionTypeCode ,m.telephone createTel," +
                    "m.createTime createTime  , " +
                    "m.state,c6.name repairState,s.name maintainName,s.telephone maintainTel ," +
                    "reSr.createTime allocationTime,re.telephone repairTel,re.name repairName,  " +
                    "m.maintenanceTime repairTime,c5.name repairResult,ev.createTime visitTime, ev.describe visitDescribe," +
                    "  reSr.state reSrState, " +
                    "c7.name visitResult,convert (varchar(20),datediff(SS,reSr.updateTime,m.maintenanceTime)/(3600*24))+'天'+  " +
                    "       convert (varchar(20),datediff(SS,reSr.updateTime,m.maintenanceTime)%(3600*24)/3600)+'小时'+   " +
                    "       convert (varchar(20),datediff(SS,reSr.updateTime,m.maintenanceTime)%(3600*24)/3600%60)+'分'  " +
                    "       as repairLong ," +
                    " (select count (1) from BUSI_RepairSupplement rep where  rep.repairApplyId=m.id  and rep.validFlag='100001' and rep.fileType='111001' ) as num " +
                    " from BUSI_MaintenanceApplication m   " +
                    " left join BASE_Equipment e on e.id=m.equipmentId   " +
                    " left join  BASE_Organization o on e.organizationId =o.id full join BASE_Organization op on o.superOrganizationId=op.id " +
                    " left join BASE_QRcode q on q.id=e.QRCode   " +
                    "  left join BASE_Staff s on s.id=m.applyStaffId   " +
                    " left join  BUSI_RepairSubmitRecord reSr on m.id=reSr.repairApplyId  and reSr.submitType='" + Constains.SUBMIT_WORK_DISTRIBUTE + "' and reSr.state in ('" + Constains.RepairSubmit_NEW + "','" + Constains.RepairSubmit_OK + "')" +
                    " left join BASE_Staff re on re.id=reSr.toStaffId   " +
                    " left join BASE_Const c6 on c6.code=m.state   " +
                    //" left join BUSI_handleResult h on h.equipmentId=m.id    " +
                    " left join BASE_Const c5 on c5.code=m.maintenanceResult  " +
                    " left join BUSI_Evaluate ev on ev.repairApplyId=m.id  " +
                    " left join BASE_Const c7 on c7.code=ev.evaluateLevel where m.validFlag='100001'   " +
                    (paramNew.get("oneCode") != null ? (" and e.oneCode like '" + paramNew.get("oneCode") + "%'") : "") +
                    (paramNew.get("brandCode") != null ? (" and e.brandCode='" + paramNew.get("brandCode") + "'") : "") +
                    (paramNew.get("organizationId") != null ? (" and e.organizationId in (" + orgs + ") ") : "") +
                    (paramNew.get("repairState") != null ? (" and m.state='" + paramNew.get("repairState") + "'") : "") +
                    (paramNew.get("name") != null ? " and( e.model like :name+'%' or q.code like :name+'%' or e.barCode like :name +'%') " : "") +
                    (paramNew.get("b_createTime") != null ? (" and m.createTime>='" + paramNew.get("b_createTime") + " 00:00:00'") : "") +
                    (paramNew.get("e_createTime") != null ? (" and m.createTime<='" + paramNew.get("e_createTime") + " 23:59:59'") : "") +
                    " order by m.createTime  desc";
            DataTable all = easyService.querySql(sql, paramNew);
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/save"})
    public AjaxDataResponseMessage insert(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                Map param = new HashMap();
                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
                Map roleId = new HashMap();
                roleId.put("userId", login.getcUserID().toString());
                Map entity = easyService.queryEntity("PM_StaffAsUser", roleId);
                if (entity != null) {
                    param.put("applyStaffId", entity.get("staffId").toString());
                }
                param.put("telephone", map.get("createTel"));
                param.put("questionTypeCode", map.get("questionTypeCode"));
                param.put("questionDescripe", map.get("questionDescribe"));
                if (map.get("id") != null && !"".equals(map.get("id"))) {
                    param.put("id", map.get("id").toString());
                } else {
                    param.put("flowCode", FlowCodeUtil.getFlowCode());
                    param.put("equipmentId", map.get("equipmentId"));
                    param.put("state", Constains.STATE_BACKGROUD_ADD);
                }
                easyService.save("BUSI_MaintenanceApplication", "id", param);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/delete"})
    public AjaxDataResponseMessage delete(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                easyService.delete("BUSI_MaintenanceApplication", "id", map);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

    //查询、高级查询
    @ResponseBody
    @RequestMapping(value = {"/queryEquipment"})
    public AjaxTableResponseMessage queryEquipment(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            String sql = "SELECT ed.name modelName,wc.warehouseId,wc.flowCode changeCode,e.*,o.name organizationName,c.name type,co.name brand,Q.code QRcode from BASE_Equipment e " +
                    " left join BASE_Organization o on o.id=e.organizationId  " +
                    " left join BASE_EquipmentDetail ed on ed.id=e.modelId  " +
                    " left join BASE_eqClass c on c.code=e.oneCode " +
                    " left join BASE_Const co on co.code=e.brandCode " +
                    " left join BASE_QRcode Q on Q.id=e.QRCode " +
                    " left join BUSI_WarehouseChange wc on wc.id=e.changeId " +
                    "where 1=1 and e.validFlag=100001 " +
                    (param.get("applyEquipment") != null ? (" and (q.code='" + param.get("applyEquipment") + "' or e.barCode='" + param.get("applyEquipment") + "')") : "");
            DataTable all = easyService.querySql(sql, param);
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/queryEquipmentH"})
    public AjaxTableResponseMessage queryEquipmentH(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            Map map = new HashMap();
//            if(param.get("applyEquipment").length()==12){
//                Map maps=new HashMap();
//                maps.put("code",param.get("applyEquipment"));
//                Map entity=easyService.queryEntity("BASE_QRcode",maps);
//                if(entity.size()>0){
//                    map.put("QRCode",entity.get("id"));
//                }
//            }else{
//                map.put("barCode",param.get("applyEquipment"));
//            }
            if (!"0".equals(param.get("type"))) {
                String code = param.get("type").toString().trim();
                map.put("oneCode", code);
            }
            if (!"0".equals(param.get("brand"))) {
                String constType = param.get("brand").toString().trim();
                map.put("brandCode", constType);
            }
            if (!"0".equals(param.get("oneOrganization"))) {
                String organization = param.get("oneOrganization").toString().trim().replaceAll(",", "");
                map.put("organizationId", organization);
            }
            String sql = "SELECT e.*,o.name organizationName,c.name type,co.name brand,Q.code QRcode from BASE_Equipment e " +
                    " left join BASE_Organization o on o.id=e.organizationId  " +
                    " left join BASE_Const c on c.code=e.oneCode " +
                    " left join BASE_Const co on co.code=e.brandCode " +
                    " left join BASE_QRcode Q on Q.id=e.QRCode " +
                    "where 1=1 and e.validFlag=100001 " +
                    (map.get("oneCode") != null ? (" and e.oneCode='" + map.get("oneCode") + "'") : "") +
                    (map.get("brandCode") != null ? (" and e.brandCode='" + map.get("brandCode") + "'") : "") +
                    (map.get("organizationId") != null ? (" and e.organizationId='" + map.get("organizationId") + "'") : "") +
                    (map.get("QRCode") != null ? (" and e.QRCode='" + map.get("QRCode") + "'") : "") +
                    (map.get("barCode") != null ? (" and e.barCode='" + map.get("barCode") + "'") : "");
            DataTable all = easyService.querySql(sql, map);
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    //附件管理
    @ResponseBody
    @RequestMapping(value = {"/queryEnclosure/{id}"})
    public AjaxTableResponseMessage queryEnclosure(String datas, @PathVariable("id") String id) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map map = new HashMap();
            map.put("repairApplyId", id);
            if (datas != null)
                map.put("dataType", datas);
            String sql = "select r.*,s.name uploadName from BUSI_RepairSupplement r " +
                    " left join BASE_Staff s on s.id=r.uploadStaffId where r.validFlag=100001 and r.dataType=:dataType" +
                    (map.get("repairApplyId") != null ? (" and r.repairApplyId=:repairApplyId") : "");
            DataTable all = easyService.querySql(sql, map);
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());

            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/enclosureSave"})
    public AjaxDataResponseMessage enclosure(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                Map param = new HashMap();
                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
                Map repairSupplement = new HashMap();
                if (map.get("filePic") != null && !"".equals(map.get("filePic")))
                    repairSupplement.put("fileAddress", FileTools.saveImage("repairPic", map.get("filePic").toString()));
                repairSupplement.put("fileDescribe", map.get("fileDescribe").toString());
                repairSupplement.put("repairApplyId", map.get("repairApplyId").toString());
                repairSupplement.put("uploadStaffId", login.getStaffId().toString());
                repairSupplement.put("dataType", map.get("dataType").toString());
                easyService.save("BUSI_RepairSupplement", "id", repairSupplement);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/enclosureDelete"})
    public AjaxDataResponseMessage enclosureDelete(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                easyService.delete("BUSI_RepairSupplement", "id", map);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

    //回访记录
    @ResponseBody
    @RequestMapping(value = {"/saveVisit"})
    public AjaxDataResponseMessage saveVisit(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                map.put("state", "200001");
                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
                Map roleId = new HashMap();
                roleId.put("userId", login.getcUserID().toString());
                Map entity = easyService.queryEntity("PM_StaffAsUser", roleId);
                if (entity != null) {
                    map.put("staffId", entity.get("staffId").toString());
                }
                map.remove("visitName");
                easyService.save("BUSI_Evaluate", "id", map);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/submitMaintenanceCenter"})
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxDataResponseMessage submitMaintenanceCenter(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
//                map.put("state","200001");
//                map.put("repairState","115001");
//                map.put("handleType","无");
//                map.put("submitType","112001");
//                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
//                Map roleId=new HashMap();
//                roleId.put("userId",login.getcUserID().toString());
//                Map entity=easyService.queryEntity("PM_StaffAsUser",roleId);
//                if(entity!=null){
//                    map.put("fromStaffId",entity.get("staffId").toString());
//                }
//                easyService.save("BUSI_RepairSubmitRecord", "id", map);
                Map query = new HashMap();
                Map update = new HashMap();
                query.put("id", map.get("repairApplyId").toString());
                update.put("state", Constains.STATE_BACKGROUD_SUBMIT_CENTERMESSAGE);
                update.put("checkTime", SqlTool.getNowTimeString());
                easyService.update("BUSI_MaintenanceApplication", query, update);

                //查询此机构的管理员 id
                String sql = "select * from BASE_Staff i where i.role='3'";
                Map param = new HashMap();
                param.put("id", map.get("equipmentId").toString());
                DataTable staffs = easyService.querySql(sql, param);
                Map entity = easyService.querySql("select a.flowCode ,c.code from BUSI_MaintenanceApplication a left join BASE_Equipment e on a.equipmentId=e.id left join BASE_QRcode c on c.id=e.QRCode where a.id=" + map.get("repairApplyId").toString(), new HashMap()).getDataRows().get(0);
                for (int i = 0; i < staffs.getDataRows().size(); i++) {
                    Map messageToAdmin = new HashMap();
                    messageToAdmin.put("template", Constains.MESSAGE_TEMPLATE_1);
                    messageToAdmin.put("staffId", staffs.getDataRows().get(i).get("id").toString());
                    Map<String, String> orgNames = equipmentService.getOrgname(map.get("equipmentId").toString());
                    messageToAdmin.put("orgName", orgNames.get("topName"));
                    messageToAdmin.put("deptName", orgNames.get("deptName"));
                    messageToAdmin.put("eCode", entity.get("code").toString());
                    messageToAdmin.put("mFlowCode", entity.get("flowCode").toString());
                    messageToAdmin.put("name", login.getcUserName());
                    messageToAdmin.put("tel", map.get("telephone"));
                    List typeList = easyService.querySql("select * from base_eqClass where code='" + map.get("eType").toString() + "'", new HashMap<>()).getDataRows();
                    if (typeList.size() >= 0) {
                        messageToAdmin.put("type", ((Map) typeList.get(0)).get("name").toString());
                    } else {
                        messageToAdmin.put("type", "其他");
                    }
                    messageToAdmin.put("first", "您有新的维修申请需要处理！");
                    messageService.saveMessages(messageToAdmin);
                }


                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/submitOrganization"})
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxDataResponseMessage submitOrganization(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
//                map.put("state","200001");
//                map.put("repairState","115001");
//                map.put("handleType","无");
//                map.put("submitType","112002");
//                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
//                Map roleId=new HashMap();
//                roleId.put("userId",login.getcUserID().toString());
//                Map entity=easyService.queryEntity("PM_StaffAsUser",roleId);
//                if(entity!=null){
//                    map.put("fromStaffId",entity.get("staffId").toString());
//                }
//                //map.put("toStaffId",);
//                easyService.save("BUSI_RepairSubmitRecord", "id", map);
                Map query = new HashMap();
                Map update = new HashMap();
                query.put("id", map.get("repairApplyId").toString());
                update.put("state", Constains.STATE_BACKGROUD_SUBMIT_MESSAGE);
                easyService.update("BUSI_MaintenanceApplication", query, update);

                //查询此机构的管理员 id
                String sql = "select * from BASE_Staff i where i.organizationId= " +
                        "( " +
                        "select  " +
                        "case when s.id is null then o.id else s.id end as id " +
                        "  " +
                        " from Base_organization o left join BASE_Organization s on o.superOrganizationId=s.id " +
                        " where o.id = (select organizationId from BASE_Equipment where  id=:id)" +
                        " ) " +
                        " and i.role='3'";
                Map param = new HashMap();
                param.put("id", map.get("equipmentId").toString());
                DataTable staffs = easyService.querySql(sql, param);
                Map entity = easyService.querySql("select a.flowCode ,c.code from BUSI_MaintenanceApplication a left join BASE_Equipment e on a.equipmentId=e.id left join BASE_QRcode c on c.id=e.QRCode where a.id=" + map.get("repairApplyId").toString(), new HashMap()).getDataRows().get(0);
                for (int i = 0; i < staffs.getDataRows().size(); i++) {
                    Map messageToAdmin = new HashMap();
                    messageToAdmin.put("template", Constains.MESSAGE_TEMPLATE_1);
                    messageToAdmin.put("staffId", staffs.getDataRows().get(i).get("id").toString());
                    Map<String, String> orgNames = equipmentService.getOrgname(map.get("equipmentId").toString());
                    messageToAdmin.put("orgName", orgNames.get("topName"));
                    messageToAdmin.put("deptName", orgNames.get("deptName"));
                    messageToAdmin.put("eCode", entity.get("code").toString());
                    messageToAdmin.put("mFlowCode", entity.get("flowCode").toString());
                    messageToAdmin.put("name", login.getcUserName());
                    messageToAdmin.put("tel", map.get("telephone"));
                    List typeList = easyService.querySql("select * from base_eqClass where code='" + map.get("eType").toString() + "'", new HashMap<>()).getDataRows();
                    if (typeList.size() >= 0) {
                        messageToAdmin.put("type", ((Map) typeList.get(0)).get("name").toString());
                    } else {
                        messageToAdmin.put("type", "其他");
                    }
                    messageToAdmin.put("first", "您有新的维修申请需要处理！");
                    messageService.saveMessages(messageToAdmin);
                }

                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/checkMaintenanceCenter"})
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxDataResponseMessage checkMaintenanceCenter(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                Map query = new HashMap();
                Map update = new HashMap();
                query.put("id", map.get("repairApplyId").toString());
                update.put("state", map.get("state").toString());
                update.put("checkTime", SqlTool.getNowTimeString());
                update.put("questionDescripe", map.get("questionDescripe").toString());
                easyService.update("BUSI_MaintenanceApplication", query, update);

                switch (map.get("state").toString()) {
                    case "201203"://提交中心
                        //查询此机构的管理员 id
                        String sql = "select * from BASE_Staff i where i.role='3'";
                        Map param = new HashMap();
                        param.put("id", map.get("equipmentId").toString());
                        DataTable staffs = easyService.querySql(sql, param);
                        Map entity = easyService.querySql("select a.flowCode ,c.code from BUSI_MaintenanceApplication a left join BASE_Equipment e on a.equipmentId=e.id left join BASE_QRcode c on c.id=e.QRCode where a.id=" + map.get("repairApplyId").toString(), new HashMap()).getDataRows().get(0);
                        for (int i = 0; i < staffs.getDataRows().size(); i++) {
                            Map messageToAdmin = new HashMap();
                            messageToAdmin.put("template", Constains.MESSAGE_TEMPLATE_1);
                            messageToAdmin.put("staffId", staffs.getDataRows().get(i).get("id").toString());
                            Map<String, String> orgNames = equipmentService.getOrgname(map.get("equipmentId").toString());
                            messageToAdmin.put("orgName", orgNames.get("topName"));
                            messageToAdmin.put("deptName", orgNames.get("deptName"));
                            messageToAdmin.put("eCode", entity.get("code").toString());
                            messageToAdmin.put("mFlowCode", entity.get("flowCode").toString());
                            messageToAdmin.put("name", login.getcUserName());
                            messageToAdmin.put("tel", map.get("telephone"));
                            List typeList = easyService.querySql("select * from base_eqClass where code='" + map.get("eType").toString() + "'", new HashMap<>()).getDataRows();
                            if (typeList.size() >= 0) {
                                messageToAdmin.put("type", ((Map) typeList.get(0)).get("name").toString());
                            } else {
                                messageToAdmin.put("type", "其他");
                            }
                            messageToAdmin.put("first", "您有新的维修申请需要处理！");
                            messageService.saveMessages(messageToAdmin);
                        }
                        break;
                    case "201621"://加入报废库
                        break;
                    case "201303"://驳回申请
                        break;
                    case "201622"://领取配件
                        break;
                    case "201629"://其他本地维修
                        break;
                }

                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }
}

